import React, { useState,useEffect, useTransition,useRef  } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select, Tabs,Tooltip,List } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { list,del,add,edit,listValue,editValue,addValue,delValue} from "@/api/modules/sccs";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { getInfo } from "@/api/login/ssoLogin";

const {TextArea} = Input;
const { Option } = Select;
const { TabPane } = Tabs; 

const sccs = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [isModalVisible2, setIsModalVisible2] = useState(false); 
  const [Title2, setTitle2] = useState("")  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [isView2, SetisView2] = useState(false)
  const [riskdistances,setRiskdistances] = useState([]); 
  const [onReloadNum, setReloadNum] = useState(0); 
  const [onReloadNum2, setReloadNum2] = useState(0); 
  const [peoplelist,setPeople] = useState([])
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 

  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 

  }, []);
  const formColumns:ProFormColumnsType[] = [ ]

  const columns: any = [
    {
      title: t('sccs.population'),
      dataIndex: ['category','population'],
      key: 'category.population',
      width: 80,
      fixed:'left',
    },
    {
      title: t('sccs.categorySccsCn'),
      dataIndex: 'categorySccsCn',
      key: 'categorySccsCn',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.categorySccsEn'),
      dataIndex: 'categorySccsEn',
      key: 'categorySccsEn',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.surfaceAreaCm2'),
      dataIndex: 'surfaceAreaCm2',
      key: 'surfaceAreaCm2',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.bodyWeightKg'),
      dataIndex: 'bodyWeightKg',
      key: 'bodyWeightKg',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.exposureMgKgBwD'),
      dataIndex: 'exposureMgKgBwD',
      key: 'exposureMgKgBwD',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.exposureMgCm2'),
      dataIndex: 'exposureMgCm2',
      key: 'exposureMgCm2',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.saf'),
      dataIndex: 'saf',
      key: 'saf',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.dailyAmountMg'),
      dataIndex: 'dailyAmountMg',
      key: 'dailyAmountMg',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.dailyAmountG'),
      dataIndex: 'dailyAmountG',
      key: 'dailyAmountG',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.remark'),
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.retentionFactor'),
      dataIndex: 'retentionFactor',
      key: 'retentionFactor',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('sccs.comment'),
      dataIndex: 'comment',
      key: 'retentionFactor',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
               <Button type="link" onClick={() => handleEdit(record)}>  
               {t('edit')} 
               </Button>  
            </>
          )}
          {/* <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>   */}
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listValue({...formData, orderby: 'a.id', order: 0})
    if(!success) return false
    let list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue(); 
    
    if(Title=='修改/Edit'){
      editValue(values).then(response => {
        message.success("成功")
        setIsModalVisible(false);
        setReloadNum(onReloadNum+1)
       });  
      }else{
          addValue(values).then(response => {
          message.success("成功")
          setIsModalVisible(false);
          setReloadNum(onReloadNum+1)
         });
      }

    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delValue(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(onReloadNum+1)
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  //select查询

  const [searchResult, setSearchResult] = useState([]);  
  const [visible, setVisible] = useState(false);  
  const [selectedResult, setSelectedResult] = useState(null);  
  
  const handleSearch = (values) => {  
    // 假设这里有一个异步的搜索函数，它返回搜索结果  
    const fakeSearch = async () => {  
      const inci = form.getFieldsValue()
      const data={
        page:1,
        limit:999,
        search:inci.inciStr,
    }
    list(data).then(res=>{
        let incis=res.data.data.page
        incis.map(item=>{
          item.name=(item.inciCn?''+item.inciCn:'') + (item.inciUs?' ,'+item.inciUs:'')
        })
        setSearchResult(incis);
        setVisible(true);  
    })
    };  
    fakeSearch()
  };  
  
  const handleSelectResult = (result) => {  
    form.setFieldsValue({ inciStr: result.name }); // 回填表单  
    form.setFieldsValue({lawInciSerial:result.serial})
    setSelectedResult(result);  
    setVisible(false); // 关闭弹窗  
  };  
  
  const modalFooter = [  
    <Button key="back" onClick={() => setVisible(false)}>  
      取消  
    </Button>,  
    <Button key="submit" type="primary" onClick={() => handleSelectResult(selectedResult)}>  
      选择  
    </Button>,  
  ];  

  //风险物质列表

  
  const formColumns2:ProFormColumnsType[] = [
  ]

  const columns2: any = [
    {
      title: t('sccs.population'),
      dataIndex: 'population',
      key: 'population',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (riskEn) => (
        <Tooltip placement="topLeft" title={riskEn}>
          {riskEn}
        </Tooltip>
      ),
    },
    {
      title: t('comment'),
      dataIndex: 'comment',
      key: 'comment',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (value) => (
        <Tooltip placement="topLeft" title={value}>
          {value}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView2(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
                <Button type="link" onClick={() => handleEdit2(record)}>  
                {t('edit')}  
                </Button> 
            </>
          )}
          {/* <Button type="link" danger onClick={() => handleDelete2(record.id)}>  
          {t('delete')}   
          </Button>   */}
   
        </>  
      ),  
    },  
  ];


  const getData2 = async (formData) => {
    const { success, data} = await list({...formData, orderby: 'id', order: 0})
    if(!success) return false
    console.log(data)
    let list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 

  const handleAdd2 = () =>{
    SetisView2(false)
    form2.resetFields()
    setTitle2("新增/New")
    showModal2()
  }

  const showModal2 = () => {  
    setIsModalVisible2(true);  
  };  

  
  const handleOk2 = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form2.getFieldsValue(); 
    if(Title2=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView2 = (record) =>{
   SetisView2(true)
   setTitle2("查看/View")
   console.log(record,'record')
   form2.setFieldsValue({ ...record });  
   setIsModalVisible2(true);  
  }

  const handleEdit2 = (record) =>{
    SetisView2(false)
    setTitle2("修改/Edit")
    console.log(record,'record')
    form2.setFieldsValue({ ...record });  
    setIsModalVisible2(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete2 = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
        }) 
      },  
    }); 
  }
  
  const handleCancel2 = () => {  
    setIsModalVisible2(false);  
  };  


   // 定义下拉框的选项  
   const options = [  
    { label: '成人', value: 2 },  
    { label: '儿童', value: 1 },  
  ];  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
    const renderOperator2 = <>
    <Button disabled={viewStatus}  type="primary" size="small" onClick={handleAdd2}>{t('add')}</Button>
  </>
  
  return (
    <div> 
      <Card>
      <Tabs type="card" defaultActiveKey="Safety SCCS Value">  
        <TabPane tab='Safety SCCS Value' key="Safety SCCS Value">  
          <MemoTable 
            name='sccs'
            formColumns={formColumns}
            columns={columns as any}
            rowKey='id'
            operator={renderOperator}
            getData={getData}
            refreshKey={onReloadNum}
          /> 
        </TabPane>  
        <TabPane tab='Category' key="Category">  
        <MemoTable 
            name='sccscategory'
            formColumns={formColumns2}
            columns={columns2 as any}
            rowKey='id'
            operator={renderOperator2}
            getData={getData2}
            refreshKey={onReloadNum2}
          /> 
        </TabPane>  
      </Tabs> 
      </Card>
       

    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              label={t('sccs.population')} 
              name="safetyCategoryId" 
              rules={[{ required: true, message: '请选择适用人群！' }]}   
            >  
                <Select disabled={isView}>  
                    {options.map((option) => (  
                      <Option key={option.value} value={option.value}>  
                        {option.label}  
                      </Option>  
                    ))}  
                  </Select>   
            </Form.Item>  
            <Form.Item  
              name="categorySccsCn"  
              label={t('sccs.categorySccsCn')} 
              rules={[{ required: true, message: '请输入产品类型！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="categorySccsEn"  
              label={t('sccs.categorySccsEn')}  
              rules={[{ required: true, message: '请输入产品类型！' }]}
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="surfaceAreaCm2"  
              label={t('sccs.surfaceAreaCm2')}  
              rules={[{ required: true, message: '请输入使用面积！' }]}
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="bodyWeightKg"  
              label={t('sccs.bodyWeightKg')}  
              rules={[{ required: true, message: '请输入体重！' }]}
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="exposureMgKgBwD"  
              label={t('sccs.exposureMgKgBwD')}  
              rules={[{ required: true, message: '请输入日均暴露量(mg/kg b.w. per day)！' }]}
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="exposureMgCm2"  
              label={t('sccs.exposureMgCm2')} 
              rules={[{ required: true, message: '请输入日均暴露量(mg/cm2)！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="saf"  
              label={t('sccs.saf')}  
              rules={[{ required: true, message: '请输入致敏评估因子(SAF)！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="dailyAmountMg"  
              label={t('sccs.dailyAmountMg')}  
              rules={[{ required: true, message: '请输入日均使用量(mg/day)' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="dailyAmountG"  
              label={t('sccs.dailyAmountG')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="remark"  
              label={t('sccs.remark')}  
            >  
              <TextArea disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="retentionFactor"  
              label={t('sccs.retentionFactor')}  
              rules={[{ required: true, message: '请输入产品驻留因子' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="comment"  
              label={t('sccs.comment')}  
            >  
              <TextArea disabled={isView}/>  
            </Form.Item> 
          </Form>  
        </Modal>  
        <Modal  
          title={Title2}
          visible={isModalVisible2}  
          onOk={handleOk2}  
          onCancel={handleCancel2}  
        >  
          <Form form={form2} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="population"  
              label={t('sccs.population')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item>  
            <Form.Item  
              name="comment"  
              label={t('comment')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item>  
          </Form>  
        </Modal> 
    </div>
  )
}
export default sccs
